package com.nerve.secondhandcar.service.impl.reception;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.ko.commons.config.PropertyConfigurer;
import org.ko.commons.util.DateUtil;
import org.ko.core.dao.support.Finder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.nerve.secondhandcar.common.C;
import com.nerve.secondhandcar.controller.model.ResaleApplyModel;
import com.nerve.secondhandcar.controller.model.reception.IndexModel;
import com.nerve.secondhandcar.dao.BrandDao;
import com.nerve.secondhandcar.dao.CarDao;
import com.nerve.secondhandcar.dao.ResaleApplyDao;
import com.nerve.secondhandcar.dao.car.CarCategoryDao;
import com.nerve.secondhandcar.domain.Car;
import com.nerve.secondhandcar.domain.ResaleApply;
import com.nerve.secondhandcar.service.reception.IndexService;

/**
 * @project: secondHandCarPlatform
 * @file: IndexServiceImpl.java
 * @package: com.nerve.secondhandcar.service.impl.reception
 * @description:
 *
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: 2014-10-22
 * @change log:
 */
@Service
@Transactional
public class IndexServiceImpl implements IndexService{
	private static final String SLIPT ="-";	//分隔符
	
	@Autowired
	private CarDao carDao;
	@Autowired
	private BrandDao brandDao;
	@Autowired
	private CarCategoryDao categoryDao;
	@Autowired
	private ResaleApplyDao applyDao;
	
	/**
	 * 加载首页数据
	 */
	@Override
	public void index(IndexModel model) throws Exception {
		int indexCategoryId = PropertyConfigurer.getInt(C.INDEX_CATEGORY_ID, 0);
		int newNumber = PropertyConfigurer.getInt(C.INDEX_NUMBER_NEW, 4);
		int specialNumber = PropertyConfigurer.getInt(C.INDEX_NUMBER_SPECIAL, 4);
		int categoryNumber = PropertyConfigurer.getInt(C.INDEX_NUMBER_CATEGORY, 4);
		System.out.println(newNumber+"  "+specialNumber+"  "+categoryNumber);
		model.setCategoryCars(listCarsByType(indexCategoryId, categoryNumber));
		model.setNewCars(listLastestCars(newNumber));
		model.setSpecialCars(listSpecialCars(specialNumber));
		
		loadBrandAndCategory(model);
	}
	
	/**
	 * 
	 * @method name: loadBrandAndCategory
	 * @return type: void
	 *	@param model
	 */
	public void loadBrandAndCategory(IndexModel model){
		model.setBrands(brandDao.brandOnIndex());
		model.setCategorys(categoryDao.list(5));
	}
	/**
	 * 获取特价车
	 * @method name: listSpecialCars
	 * @return type: List<Car>
	 *	@return
	 */
	private List<Car> listSpecialCars(int size){
		Finder f = Finder.create("FROM Car where specialPrice=1");
		f.append(" and trash!="+C.DELETE_ENTITY);
		f.append(" order by clickAmount desc");
		f.setMaxResults(size);
		return carDao.find(f);
	}
	/**
	 * 获取最新上架的车
	 * @method name: listSpecialCars
	 * @return type: List<Car>
	 *	@return
	 */
	private List<Car> listLastestCars(int size){
		Finder f = Finder.create("FROM Car where status="+Car.PENDING); 
		f.append(" and trash!="+C.DELETE_ENTITY);
		f.append(" order by clickAmount desc");
		f.setMaxResults(size);
		return carDao.find(f);
	}
	/**
	 * 获取指定类型的车
	 * 如果categoryId 为0，则列出最受欢迎的汽车
	 * 
	 * 默认的id在 sysconfig.properties 中配置
	 * @method name: listSpecialCars
	 * @return type: List<Car>
	 *	@return
	 */
	private List<Car> listCarsByType(int categoryId,int size){
		Finder f = Finder.create("FROM Car where 1=1");
		if(categoryId >0){
			f.append(" and category.id="+categoryId);
		}
		f.append(" and trash!="+C.DELETE_ENTITY);
		f.append(" order by clickAmount desc");
		f.setMaxResults(size);
		
		return carDao.find(f);
	}
	@Override
	public void detail(IndexModel model) throws Exception {
		Car car = carDao.get(model.getId());
		Assert.notNull(car, "你查看的汽车不存在");
		//点击+1
		carDao.runHql("update Car set clickAmount=clickAmount+1 where id="+model.getId() );
		model.setCar(car);
	}
	
	@Override
	public void list(IndexModel model) throws Exception {
		Finder f = Finder.create("FROM Car as c where trash!="+C.DELETE_ENTITY);
		
		//如果有品牌关键字，就进行like搜索
		if(StringUtils.hasText(model.getBrand())){
			f.append(" and c.fullName like :brand");
			f.setParam("brand", like(model.getBrand()));
		}
		
		//判断汽车类型
		if(model.getCategoryId()>0){
			f.append(" and c.category.id="+model.getCategoryId());
		}
		
		//判断车身类型
		if(StringUtils.hasText(model.getType())){
			f.append(" and c.configure.category like :category");
			f.setParam("category", like(model.getType()));
		}
		
		//判断里程
		if(StringUtils.hasText(model.getMileage())){
			f.append(buildRange(model.getMileage(), "c.mileage"));
		}
		
		//判断价格
		if(StringUtils.hasText(model.getPrice())){
			f.append(buildRange(model.getPrice(), "c.price"));
		}
		
		//判断车龄
		/*
		 * 这个就要先做一个转化
		 * 如，参数值为 0-2，则想要查询的是车龄在2年内的车子
		 * 这里判断的字段是 regYear
		 * 
		 */
		if(StringUtils.hasText(model.getYear())){
			String ys[] = model.getYear().trim().split(SLIPT);
			
			String format = "yyyy";
			Calendar c = Calendar.getInstance();
			for(int i=0;i<ys.length;i++){
				if(ys[i].length()>0){
					try{
						int year = Integer.valueOf(ys[i]);
						c.add(Calendar.YEAR, -1*year);
						
						ys[i] = DateUtil.toString(c.getTime(), 	format);
					}catch(Exception e){
						throw new Exception("车龄参数格式不正确！");
					}
				}
			}
			
			f.append(buildRange(ys[1]+SLIPT+ys[0], "c.regYear"));
		}
		
		//判断变速箱
		if(StringUtils.hasText(model.getShift())){
			f.append(" and c.configure.bottom.shift like :shift");
			f.setParam("shift", like(model.getShift()));
		}
		
		//判断特价
		if(model.getSpecial() == 1){
			f.append(" and c.specialPrice=1");
		}
		
		//判断车况
		if(model.getGrade()>0){
			f.append(" and c.report.grade="+model.getGrade());
		}
		
		f.append(" order by postDate desc,clickAmount desc");
		System.out.println("SQL:"+f.getOrigHql());
		carDao.find(f, model);
		
		loadBrandAndCategory(model);
	}
	private String like(String str){
		return "%"+str+"%";
	}
	/**
	 * <pre>
	 * 构建范围
	 * 返回示例： 
	 * var = mileage
	 * 1-4	(mileage>='1' and mileage <='4')
	 * 4-	(mileage>='4')
	 * -4	(mileage <='4')
	 * 
	 * 为了兼容，统一使用串的对比方式
	 * </pre>
	 * @method name: buildRange
	 * @return type: String
	 *	@param range	范围，如1-4
	 *	@param var		字段名，如里程mileage
	 *	@return			
	 */
	public String buildRange(String range, String var){
		if(range.indexOf(SLIPT)==-1){
			return "";
		}
		String temp[] = range.trim().split(SLIPT);
		
		String left = "";
		String right = "";
		
		if(temp.length>0&&temp[0].length()>0){
			left = (var+">='"+temp[0]+"'");
		}
		if(temp.length>1&&temp[1].length()>0){
			right = (var+"<='"+temp[1]+"'");
		}
		if(left.length()>0 && right.length()>0){
			left+=" and ";
		}
		
		return " and ("+left+right+")";
	}
	
	//保存转售申请
	@Override
	public void create(ResaleApplyModel model) throws Exception {
		ResaleApply entity=model.getBean();
		if(entity != null){
			if(entity.isUsable()){
				//所有非估价的都设置为转售
				if(entity.getCategory()!=ResaleApply.ASSESSMENT)
					entity.setCategory(ResaleApply.RESALE);
//				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式	
//				String date=df.format(new Date());
//				Date d=df.parse(date);
				entity.setPostDate(new Date());
				applyDao.merge(entity);
			}else{
				entity.setPostDate(new Date());
				applyDao.save(entity);
			}
		}
	}
}